package com.dream.libxrec.camera;

import android.media.Image;
import android.media.ImageWriter;
import android.util.Log;
import android.view.Surface;

/**
 * 绘制Surface的方案二
 */
public class CameraPreviewHelper2 {
    private volatile ImageWriter mImageWriter = null;
    private boolean isWaitValid = false;
    private boolean isAllowBack = false;
    private Surface mSurface;

    /**
     * 设置预览
     * @param surface
     * @param isAllowBack 进入后台是否依旧保留，如果不允许，当Surface被销毁后，预览也会被销毁,
     *                    反之，会等待Surface恢复后继续绘制
     */
    public synchronized void setPreview(Surface surface,
                                        boolean isAllowBack) {
        if (surface == null){
            mSurface = null;
            return;
        }

        this.isAllowBack = isAllowBack;
        if (!surface.isValid()){
            isWaitValid = true;
            mSurface = surface;
            return;
        }
        mSurface = surface;
        initSurface(surface);
    }

    private void initSurface(Surface surface) {
        if (mImageWriter != null){
            mImageWriter.close();
            mImageWriter = null;
        }

        if (surface != null){
            mImageWriter = ImageWriter.newInstance(surface,2);
        }
    }


    public synchronized void draw(Image image){

        if (mSurface == null){
            return;
        }

        if (!mSurface.isValid()){
            if (!isWaitValid && !isAllowBack) {
                //释放资源
                setPreview(null,false);
            }

            return;
        }

        try {
            if (isWaitValid){
                isWaitValid = false;
                initSurface(mSurface);
            }

            if (mImageWriter != null){
                try {
                    //将摄像头画面绘制到Surface上
                    mImageWriter.queueInputImage(image);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception ignored){}
    }

}
